package com.dongdongshop.controller;

import com.alibaba.fastjson.JSONObject;
import com.dongdongshop.constant.HttpResultEnum;
import com.dongdongshop.data.DataResult;
import com.dongdongshop.pojo.cart.Cart;
import com.dongdongshop.pojo.order.TbOrderItem;
import com.dongdongshop.service.cart.CartService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author Eayon
 * @Date 2020/4/4 10:11
 */
@RestController
@RequestMapping("cart")
public class CartController {

    private static final Logger log = LoggerFactory.getLogger(CartController.class);

    @Autowired
    private CartService cartService;

    /**
     * 根据用户名，从缓存中获取该用户购物车
     * @param username
     * @return
     */
    @GetMapping("/{username}")
    public DataResult<List<Cart>> findCarttsByUsernameForCache(@PathVariable("username")String username){
        List<Cart> cartList = null;
        try {
            log.info("从redis中获取该用户的购物车数据：参数{}",username);
            cartList = cartService.findCarttsByUsernameForCache(username);
        }catch (Exception e){
            log.error("缓存中获取用户购物车数据异常",e);
            return new DataResult<List<Cart>>(HttpResultEnum.ERROR.getCode(),HttpResultEnum.ERROR.getMessage());
        }
        return new DataResult<List<Cart>>(HttpResultEnum.SUCCESS.getCode(),HttpResultEnum.SUCCESS.getMessage(),cartList);
    }

    /**
     * 合并缓存和cookie购物车
     * @param carsByCache
     * @param carsByCookie
     * @return
     */
    @GetMapping("/mergeCarList")
    public DataResult<List<Cart>> mergeCartList(String carsByCache, String carsByCookie) {
        List<Cart> carsByCache1 = JSONObject.parseArray(carsByCache, Cart.class);
        List<Cart> carsByCookie1 = JSONObject.parseArray(carsByCookie, Cart.class);
        if(carsByCache == null){
            carsByCache1 = new ArrayList<Cart>();
        }
        if(carsByCookie1 == null){
            carsByCookie1 = new ArrayList<Cart>();
        }
        log.info("进入合并购物车方法，缓存购物车：{}，cookie购物车：{}",carsByCache1,carsByCookie1);
        List<Cart> carts = null;
        try {
            carts = cartService.mergeCartList(carsByCache1,carsByCookie1);
        }catch (Exception e){
            log.error("合并购物车异常",e);
            return new DataResult<List<Cart>>(HttpResultEnum.ERROR.getCode(),HttpResultEnum.ERROR.getMessage());
        }
        return new DataResult<List<Cart>>(HttpResultEnum.SUCCESS.getCode(),HttpResultEnum.SUCCESS.getMessage(),carts);
    }

    /**
     * 将购物车写入redis
     * @param cartList
     * @param username
     */
    @PostMapping("/save")
    public void save(@RequestParam("cartList")String cartList,@RequestParam("username")String username) {
        List<Cart> carts = JSONObject.parseArray(cartList, Cart.class);
        if(cartList == null){
            carts = new ArrayList<Cart>();
        }
        log.info("成功将购物车写入redis   购物车：{}，用户名：{}",carts,username);
        cartService.saveCartListToRedis(carts,username);
    }

    /**
     * 添加商品到购物车进行重新组装
     * @param cartList
     * @param itemId
     * @param num
     * @return
     */
    @GetMapping("/addGoodsToCartList")
    public DataResult<List<Cart>> addGoodsToCartList(String cartList, String itemId, String num) {
        List<Cart> carts = null;
        try {
            List<Cart> cartList1 = JSONObject.parseArray(cartList, Cart.class);
            if(cartList1 == null){
                cartList1 = new ArrayList<>();
            }
            Long itemId1 = Long.parseLong(itemId);
            Integer num1 = Integer.parseInt(num);
            carts = cartService.addGoodsToCartList(cartList1,itemId1,num1);
        }catch (Exception e){
            log.error("合并购物车异常",e);
            return new DataResult<List<Cart>>(HttpResultEnum.ERROR.getCode(),HttpResultEnum.ERROR.getMessage());
        }
        return new DataResult<List<Cart>>(HttpResultEnum.SUCCESS.getCode(),HttpResultEnum.SUCCESS.getMessage(),carts);
    }


    /**
     * 根据用户选择的itemId去该用户的购物车中获取并组装成购物车集合返回
     * @param itemIds
     * @param username
     * @return
     */
    @GetMapping("/getItemsByItemId")
    public DataResult<List<Cart>> getItemsByItemId(String itemIds,String username){
        List<Long> itemIdList = JSONObject.parseArray(itemIds, Long.class);
        List<Cart> carts = null;
        try {
            carts = cartService.getItemsByItemId(itemIdList,username);
        }catch (Exception e){
            log.error("获取被选中的购物车商品异常",e);
            return new DataResult<List<Cart>>(HttpResultEnum.ERROR.getCode(),HttpResultEnum.ERROR.getMessage());
        }
        return new DataResult<List<Cart>>(HttpResultEnum.SUCCESS.getCode(),HttpResultEnum.SUCCESS.getMessage(),carts);
    }


    /**
     * 删除购物车中的商品明细，并返回删除过后的购物车集合
     * @param cartsList
     * @param itemId
     * @return
     */
    @PostMapping("/deleteCartOrderItem")
    public DataResult<List<Cart>> deleteCartOrderItem(@RequestBody List<Cart> cartsList,@RequestParam("itemId") Long itemId){
        List<Cart> carts = null;
        try {
            carts = cartService.deleteCartOrderItem(cartsList,itemId);
        }catch (Exception e){
            log.error("删除购物车中的商品明细异常",e);
            return new DataResult<List<Cart>>(HttpResultEnum.ERROR.getCode(),HttpResultEnum.ERROR.getMessage());
        }
        return new DataResult<List<Cart>>(HttpResultEnum.SUCCESS.getCode(),HttpResultEnum.SUCCESS.getMessage(),carts);
    }
}
